<!--
 * @Descripttion:菜品分类报表
 * @Author: 森哥
 * @Date: 2022-11-08 14:20:57
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-09-22 10:47:41
-->
<template>
  <div>
    <div class="time-division-content-wrap">
      <!-- 左边盒子 -->
      <div class="left-box">
        <div class="left-box-title">菜品分类报表</div>
        <!-- 头部查询项 -->
        <div class="search-box">
          <el-date-picker
            v-model="dateRangeList"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
          <span class="search-btn" @click="fetchCategoryReport">查询</span>
        </div>

        <!-- 桌台分类显示 -->
        <div class="category-title">桌台分类显示</div>
        <!-- 桌台分类循环项 -->
        <div class="list-box">
          <div class="loop-box" v-loading="tableCategoryLoading" element-loading-text="加载中...">
            <div
              class="list-item"
              :class="{ active: searchParam.desk_category_list.length === 0 }"
              @click="handleActionTable(-1)"
            >
              全部
            </div>
            <div
              v-for="(item, index) in tableCategoryList"
              class="list-item"
              :class="{ active: searchParam.desk_category_list.includes(item.id) }"
              :key="index"
              @click="handleActionTable(index)"
            >
              {{ item.name }}
            </div>
          </div>

          <div class="table-data-summary">共{{ tableCategoryList.length }}条</div>
        </div>
        <!-- 菜品分类显示 -->
        <div class="category-title">菜品分类显示</div>
        <!--  菜品分类循环项 -->
        <div class="list-box">
          <div class="loop-box" v-loading="foodCategoryLoading" element-loading-text="加载中...">
            <div
              class="list-item"
              :class="{ active: searchParam.food_category_list.length === 0 }"
              @click="handleActionFood(-1)"
            >
              全部
            </div>
            <div
              v-for="(item, index) in foodCategoryList"
              class="list-item"
              :class="{ active: searchParam.food_category_list.includes(item.id) }"
              :key="index"
              @click="handleActionFood(index)"
            >
              {{ item.name }}
            </div>
          </div>

          <div class="dishes-data-summary">共{{ foodCategoryList.length }}条</div>
        </div>
        <div class="data-summary-box">
          <div class="sumary-btn-group">
            <span class="cancel-closing" @click="printTicket">打印</span>
            <span class="cancel" @click="handleAction">返回</span>
          </div>
        </div>
      </div>
      <!-- 右边盒子 -->
      <div class="right-box">
        <FoodCategorySummaryCard :dishesList="dishesList" :loading="reportLoading" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import FoodCategorySummaryCard from './components/FoodCategorySummaryCard.vue'
import {
  getCategoryList,
  foodCategory,
  categoryReport as getCategoryReport
} from '@/api/foodCatgorySummary'
import { getNowDateAndTime } from '@/utils/index'

const router = useRouter()

// 子组件渲染的菜品分类列表
const dishesList = ref({})
const dateRangeList = ref([])
// 查询参数
const searchParam = ref({
  desk_category_list: [],
  food_category_list: []
})
// 桌台分类列表
const tableCategoryList = ref([])
// 菜品分类列表
const foodCategoryList = ref([])
// 加载状态
const tableCategoryLoading = ref(false)
const foodCategoryLoading = ref(false)
const reportLoading = ref(false)

// 点击激活桌台分类样式
const handleActionTable = index => {
  if (index === -1) {
    searchParam.value.desk_category_list = []
  } else {
    const isExist = searchParam.value.desk_category_list.find(
      item => item === tableCategoryList.value[index].id
    )
    if (!isExist) {
      searchParam.value.desk_category_list.push(tableCategoryList.value[index].id)
    } else {
      searchParam.value.desk_category_list = searchParam.value.desk_category_list.filter(
        item => item !== tableCategoryList.value[index].id
      )
    }
  }
  fetchCategoryReport()
}

// 点击激活菜品分类显示样式
const handleActionFood = index => {
  if (index === -1) {
    searchParam.value.food_category_list = []
  } else {
    const isExist = searchParam.value.food_category_list.find(
      item => item === foodCategoryList.value[index].id
    )
    if (!isExist) {
      searchParam.value.food_category_list.push(foodCategoryList.value[index].id)
    } else {
      searchParam.value.food_category_list = searchParam.value.food_category_list.filter(
        item => item !== foodCategoryList.value[index].id
      )
    }
  }
  console.log(searchParam.value.food_category_list)
  fetchCategoryReport()
}

const getCategoryListFn = () => {
  tableCategoryLoading.value = true
  return getCategoryList()
    .then(res => {
      tableCategoryList.value = [...res.data]
    })
    .catch(err => {
      ElMessage.error('获取桌台分类失败: ' + (err.message || '未知错误'))
      throw err
    })
    .finally(() => {
      tableCategoryLoading.value = false
    })
}

const foodCategoryFn = data => {
  foodCategoryLoading.value = true
  return foodCategory(data)
    .then(res => {
      foodCategoryList.value = [...res.data]
    })
    .catch(err => {
      ElMessage.error('获取菜品分类失败: ' + (err.message || '未知错误'))
      throw err
    })
    .finally(() => {
      foodCategoryLoading.value = false
    })
}

const fetchCategoryReport = () => {
  if (!dateRangeList.value || dateRangeList.value.length < 2) {
    ElMessage.warning('请选择日期范围')
    return
  }
  const startDate = new Date(dateRangeList.value[0])
  const endDate = new Date(dateRangeList.value[1])
  if (startDate > endDate) {
    ElMessage.warning('开始日期不能晚于结束日期')
    return
  }
  let start_time = ''
  let end_time = ''
  start_time = dateRangeList.value[0] + ' 00:00:00'
  end_time = dateRangeList.value[1] + ' 23:59:59'
  if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
    ElMessage.error('无效的日期格式')
    return
  }
  reportLoading.value = true
  getCategoryReport({
    // search_name参数不存在，已移除
    start_time: start_time,
    end_time: end_time,
    desk_category_list: searchParam.value.desk_category_list,
    food_category_list: searchParam.value.food_category_list,
    print: '0'
  })
    .then(res => {
      dishesList.value = res.data.detail
      console.log(dishesList.value)
    })
    .catch(err => {
      ElMessage.error('获取数据失败: ' + (err.message || '未知错误'))
    })
    .finally(() => {
      reportLoading.value = false
    })
}

const handleAction = () => {
  router.back()
}

const printTicket = () => {
  let start_time = ''
  let end_time = ''
  if (dateRangeList.value) {
    start_time = dateRangeList.value[0] + '00:00:00'
    end_time = dateRangeList.value[1] + '23:59:59'
  }
  getCategoryReport({
    start_time: start_time,
    end_time: end_time,
    desk_category_list: searchParam.value.desk_category_list,
    food_category_list: searchParam.value.food_category_list,
    print: '1'
  })
    .then(res => {
      ElMessage.success('推送打印成功')
    })
    .catch(err => {
      ElMessage.error('打印失败: ' + (err.message || '未知错误'))
    })
}

onMounted(() => {
  const { currentNowDate } = getNowDateAndTime()
  dateRangeList.value = [currentNowDate, currentNowDate]
  const promise = []
  promise.push(getCategoryListFn())
  promise.push(
    foodCategoryFn({
      parent_id: 0
    })
  )
  Promise.all(promise).then(() => {
    fetchCategoryReport()
  })
})
</script>

<style lang="scss" src="./modules/foodCategorySummary.scss" scoped></style>
